package com.zzlzd.drp.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.zzlzd.drp.config.BaseConfig;

import java.io.InputStream;

public class QiniuUtils {

    private BaseConfig baseConfig;

    public QiniuUtils(BaseConfig baseConfig) {
        this.baseConfig = baseConfig;
    }

    /***
     * 删除文件
     * @param key
     */
    public void delFile(String key){
        Configuration cfg = new Configuration(Region.huanan());
        Auth auth = Auth.create(baseConfig.getAccessKey(), baseConfig.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(baseConfig.getBucket(), key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

    /****
     * 上传文件
     * @param type
     * @param filename
     * @param stream
     * @return
     */
    public DefaultPutRet uploadFile(int type, String filename, InputStream stream){
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(baseConfig.getAccessKey(), baseConfig.getSecretKey());
        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"fsize\":$(fsize)}");
        putPolicy.put("fileType",type);
        long expireSeconds = 3600;
        String upToken = auth.uploadToken(baseConfig.getBucket(), null, expireSeconds, putPolicy);
        try {
            Response response = uploadManager.put(stream,filename,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return null;
    }

}
